package com.qf.fmall.shopcart.controller;

import com.qf.fmall.shopcart.entity.ShoppingCart;
import com.qf.fmall.shopcart.service.IShoppingCartService;
import com.qf.fmall.utils.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wbw
 * @since 2023-11-30
 */
@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/shopcart")
public class ShoppingCartController {
    @Autowired
    private IShoppingCartService shoppingCartService;
    @GetMapping("/listbycids")
    public ResultVo listbycids(Integer[] cids){
        log.info("查询购物车信息 cids={}",cids);
        if (cids.length==0){
           return ResultVo.notok(-10011,"没有传入购物车id");
        }
        List<Integer> list = Arrays.asList(cids);

        List<ShoppingCart> data = shoppingCartService.listbycids(list);

        return ResultVo.ok(10000,"success",data);
    }
    @GetMapping("/list")
    public ResultVo cartList(Integer userId){
        log.info("查询购物车信息：userid={}",userId);
        if (userId==null){
            return ResultVo.notok(-10009,"用户id不为空");
        }
         List<ShoppingCart> data = shoppingCartService.cartList(userId);
        return ResultVo.ok(10000,"success",data);

    }
    @PostMapping("/add")
    public ResultVo add(@RequestBody ShoppingCart cart){
        log.info("接收到的购物车对象为：cart={}",cart);
        String userId = cart.getUserId();
        Integer productId = cart.getProductId();
        String skuId = cart.getSkuId();
        if (userId==null||productId==null||skuId==null){
            return ResultVo.notok(-10008,"购物车必传id为空");
        }
//        shoppingCartService.addCart(cart);
        //数据存入数据库

        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(date);
        cart.setCartTime(format);
        shoppingCartService.save(cart);

        return ResultVo.ok(10000,"success");
    }


    @PutMapping ("/update/{cid}/{num}")
    public ResultVo updata(@PathVariable("cid") Integer cid ,@PathVariable("num") Integer num){
        log.info("更新购物车数量，cid={},num={}",cid,num);
        if (cid==null||num==null){
            return ResultVo.notok(-10012,"更新购物车参数错误");
        }
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setCartId(cid);
        shoppingCart.setCartNum(num+"");
        shoppingCartService.updateById(shoppingCart);
        return ResultVo.ok(10000,"success");

    }
}
